#include "verycd_downThread.h"
#include "verycd_downMain.h"
#include <wx/app.h>
#include <wx/sstream.h>
#include <wx/protocol/http.h>
#include <wx/msgdlg.h>
#include <wx/gauge.h>
wxMutex muta;
void* vd_Thread::Entry()
{
    wxString a;
    int b,c;
    bool l;
    do
    {
        l=httpDown(&a,dom,ur);
    }while (l==false || a.Trim().IsEmpty());

    b=a.find("ed2k://");
    c=a.find('"',b);
    {
        wxMutexLocker lock(muta);
        if (lock.IsOk())
        {
            lin->at(inde)=a.Mid(b,c-b);
            (*cb)++;
        }

    }

    return NULL;
}

void vd_Thread::setarg(vector<wxString>* link,int index,wxString domain,wxString url,int* callback)
{
    lin=link;
    inde=index;
    cb=callback;
    dom=domain;
    ur=url;
}

bool vd_Thread::httpDown(wxString* code,const wxString domain,const wxString url)
{
    //    wxString msg = wxbuildinfo(long_f);
//    wxMessageBox(msg, _("Welcome to..."));
    wxHTTP get;
    get.SetHeader(_T("Content-type"), _T("text/html; charset=utf-8"));
    get.SetTimeout(10);
    while (!get.Connect(domain)) // only the server, no pages here yet ¡­
        wxSleep(5);
    wxApp::IsMainLoopRunning(); // should return true
// use _T(¡°/¡±) for index.html, index.php, default.asp, etc.
    wxInputStream *httpStream = get.GetInputStream(url);

// wxLogVerbose( wxString(_T(¡± GetInputStream: ¡°)) << get.GetResponse() << _T(¡°-¡±) << //((resStream)? _T(¡°OK ¡°) : _T(¡°FAILURE ¡°)) << get.GetError() );
    if (get.GetError() == wxPROTO_NOERR)
    {
        //wxString res;
        wxStringOutputStream out_stream(code);
        httpStream->Read(out_stream);
        wxDELETE(httpStream);
        get.Close();
        return true;
        //wxMessageBox(res);

// wxLogVerbose( wxString(_T(¡± returned document length: ¡°)) << res.Length() );
    }
    else
    {
        wxDELETE(httpStream);
        get.Close();
        return false;
    }

}
